<template>
  <div>
    <!-- 搜索框 -->
    <van-search v-model="value" placeholder="请输入关键词" @input="On_Input" @search="onSearch" />
    <div v-show="TOPSEARCH">
      <!-- 热搜部分 -->
      <van-divider>热搜词</van-divider>
      <van-grid :column-num="5" :border="false">
        <van-grid-item
          v-for="(item,index) in listItem"
          :key="index"
          :text="item"
          @click="TopSearch(item)"
        />
      </van-grid>

      <!-- 历史记录 -->
      <van-divider>
        历史记录
        <van-icon name="delete" @click="del" />
      </van-divider>
      <van-grid :column-num="5" :border="false">
        <van-grid-item v-for="(item,index) in historyList" :key="index" :text="item" />
      </van-grid>
    </div>

    <!-- 展示搜索内容 -->
    <van-cell-group
      v-for="(item,index) in list"
      :key="index"
      v-show="isShow"
      @click="OnClick(item)"
    >
      <van-cell :title="item.title" />
    </van-cell-group>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      TOPSEARCH: true, //显示隐藏热搜历史记录
      isShow: false, //显示隐藏搜索结果
      value: "", //搜索框内
      list: [], //搜索内容数组
      historyList: [], //历史记录
      listItem: [
        "游戏",
        "财经",
        "疫情",
        "娱乐",
        "美国",
        "体育",
        "社会",
        "军事",
        "推荐",
      ], //热搜词
    };
  },
  created() {
    let historyList = localStorage.historyList;
    if (this.historyList) {
      this.historyList = JSON.parse(historyList);
    }
  },
  methods: {
    //
    On_Input() {
        if(this.value !== ''){
            this.TOPSEARCH = false
        }
      this.isShow = true;
      axios
        .get("http://api.kudesoft.cn/news/list", {
          params: {
            kw: this.value,
          },
        })
        .then((res) => {
          this.list = res.data.result.data;
          console.log(this.list);
        })
        .catch((err) => {
          console.log("加载时间过长");
        });
      if (this.value == "") {
        this.isShow = false;
        this.TOPSEARCH = true
      }
    },
    OnClick(item) {
      window.location.href = item.url;
      this.historyList.push(this.value);
      this.save();
    },
    onSearch() {
      if (this.value === "") {
        return;
      } else {
        this.historyList.push(this.value);
        this.save();
      }
    },
    TopSearch(item) {
      console.log(item);
      this.$router.push({
        path: "/",
        query: {
          item: item,
        },
      });
      this.historyList.push(item);
      this.save();
    },
    del() {
      this.historyList = "";
      this.save();
    },
    save() {
      localStorage.historyList = JSON.stringify(this.historyList);
    },
  },
};
</script>

<style>
</style>